<?php
namespace pan;
use ZipStream;
use Apfelbox\FileDownload\FileDownload;
use PHPMailer\PHPMailer\PHPMailer;
/*
 * 工具栏
 * */
class Tools
{
    /*格式化路径
     * 把路径去空格，去掉/static的/
     * */
    public static function format($url)
    {
        $url = trim($url);
        $Newurl = preg_replace("/^\//", '', $url);
        if (isset($Newurl)) {
            return $Newurl;
        }
        return $url;
    }
    /*
     * 压缩成zip下载
     *  @$urls 必须为数组
     *  @$name  重复名压缩包的名字
     * */
    public static function compress($urls, $name = 'example.zip')
    {
        try {
            $options = new ZipStream\Option\Archive();
            $options->setSendHttpHeaders(true);
            $zip = new ZipStream\ZipStream($name, $options);
            foreach ($urls as $key => $url) {
                $zip->addFileFromPath(basename($url), self::format($url));
            }
            $zip->finish();
        } catch (\Ecexption $e) {
           return $e->getMessage();
        }
    }
    /*
     *下载功能
     * @$url   字符串
     * @$name 重复名下载文件的名字
     * */
    public static function download($url, $name)
    {
        try {
            $fileDownload = FileDownload::createFromFilePath(self::format($url));
            $fileDownload->sendDownload($name);
        } catch (\Execption $e) {
           return $e->getMessage();
        }
    }
    /*
     * 上传单一文集
     * @$file  文件类型
     * @$size  文件限制大小  int
     * @$ext   文件限制后缀名 string
     * */
    public static function upload($file,$ext ='jpg,png,gif,pptx,docx,txt',$size = 2000000)
    {
        if(empty($file)){
            return 'The file is empty';
        }
        try {
            $info = $file->validate(['size' => $size, 'ext' => $ext])
                ->move('uploads');
            if ($info) {
                return [
                    'path' => $info->getSaveName(),
                    'md5Name' => $info->getFilename(),
                    'ext' => $info->getExtension()
                ];
            } else {
               return $file->getError();
            }
        } catch (\Execption $e) {
           return $e->getMessage();
        }
    }
    /*多文件上传
     * @$files 必须为数组 如：file[] header设置为multipart/form-data
     * @$size  文件限制大小  int
     * @$ext   文件限制后缀名 string
     * */
    public static function uploads($files,$ext = 'jpg,png,gif,pptx,docx,txt',$size = 2000000)
    {
        if(!is_array($files)){
            return 'Is not an array';
        }
        try {
            $arr=[];
            foreach ($files as $key=>$file) {
                $info = $file->validate(['size' => $size, 'ext' => $ext])
                    ->move('uploads');
                if ($info) {
                    $arr[]=[
                        'path'.$key=> $info->getSaveName(),
                        'md5Name'.$key=> $info->getFilename(),
                        'ext'.$key => $info->getExtension()
                    ];
//                    $arr['path'.$key]=$info->getSaveName();
//                    $arr['md5Name'.$key]=$info->getFilename();
//                    $arr['ext'.$key]=$info->getExtension();
                } else {
                    return $file->getError();
                }
            }
            return $arr;
        } catch (\Execption $e) {
           return $e->getMessage();
        }
    }
    /*
     * @subject  title string require 邮件标题
     * @body     content  string require 邮件内容
     * @addressArr  addresses array require  收件人
     * @from    Send an address  string require 发件人地址
     * @fromName  Name of sender string  optional  发件人名字（收到邮件显示的标题）
     * @host  localhost string require  域名
     * @username   accountName of sender string    optional  邮箱服务器账户
     * @password   accountPassword of sender string optional 邮箱服务器密码
     * @AttachmentArr  attachments  array optional  $Key=>name of attachment  附件
     * */
    public static function  email($subject,$body,$addressArr,$from,$fromName,
                                  $host,$username='',$password='',$AttachmentArr=[]){
        $mail = new PHPMailer(true);
        try {
//            $mail->SMTPDebug = SMTP::DEBUG_SERVER;
            $mail->isSMTP();
            $mail->Host= $host;
            $mail->SMTPAuth   = true;
            if($username!='' && $password!=''){
                $mail->Username = $username;
                $mail->Password = $password;
            }
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = 587;
            $mail->setFrom($from, $fromName);
            foreach ($addressArr as $val){
                $mail->addAddress($val);
            }
            if(!empty($AttachmentArr)){
                foreach ($AttachmentArr as $key=>$val){
                    $mail->addAttachment(self::format($val),$key);
                }
            }
            $mail->isHTML(true);
            $mail->Subject =$subject;
            $mail->Body    = $body;
            $mail->send();
            return [
                'msg'=>'succeese'
            ];
        }catch (\Execption $e){
            return [
                'msg'=>'error',
                'error'=>$mail->ErrorInfo
            ];
        }
    }
}